package com.epfresh.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.ucrop.PhotoCore;
import com.epfresh.api.utils.AppUtils;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.T;
import com.epfresh.bean.StoreDetail;
import com.epfresh.global.BaseActivity;
import com.epfresh.R;
import com.epfresh.constant.Constant;
import com.epfresh.global.DataManager;
import com.epfresh.jsbridge.BridgeHandler;
import com.epfresh.jsbridge.BridgeWebView;
import com.epfresh.jsbridge.BridgeWebViewClient;
import com.epfresh.jsbridge.CallBackFunction;
import com.epfresh.wxapi.WXPayEntryActivity;
import com.google.gson.Gson;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wzh on 2016/5/6.
 */
public class H5OrderDetailActivity extends BaseActivity implements PhotoCore.PhotoResult {
    private BridgeWebView webview;
    private ProgressBar pb;
    private String url;
    private String title;
    private int pushType = 2;

    private String orderId;
    //是否需要刷新订单
    private boolean isRefresh;

    private PhotoCore photoCore;
    private String filePath = FileUtil.getImgCacheDir() + "/" + "comment";
    private Map<String, String> titleMap = new HashMap<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_js_web);

        filePath = filePath + "_" + getUser().getAccountId();
        photoCore = new PhotoCore(this, this);
        photoCore.setResultHeight(200);
        photoCore.setResultWidth(200);

        if (savedInstanceState != null) {
            url = savedInstanceState.getString(Constant.KEY_WEB_URL);
            title = savedInstanceState.getString(Constant.KEY_WEB_TITLE);
            pushType = savedInstanceState.getInt("pushType");
            orderId = savedInstanceState.getString("orderId");
        } else {
            url = getIntent().getStringExtra(Constant.KEY_WEB_URL);
            title = getIntent().getStringExtra(Constant.KEY_WEB_TITLE);
            pushType = getIntent().getIntExtra("pushType", 2);
            orderId = getIntent().getStringExtra("orderId");
        }

        pushType = getIntent().getIntExtra("pushType", 2);
//        if (TextUtils.isEmpty(url)) {
//            finish();
//        } else {
        ivBack.setVisibility(View.VISIBLE);
        toolbarTitle.setVisibility(View.VISIBLE);
        toolbarTitle.setText(title == null ? "" : title);
        pb = (ProgressBar) findViewById(R.id.pb);
        webview = (BridgeWebView) findViewById(R.id.wv);
        pb.setVisibility(View.VISIBLE);
        webViewSetting();
        url = getOrderUrl();
        if (!TextUtils.isEmpty(url)) {
            webview.loadUrl(url);
            Log.e("url", "" + url);
        } else {
            toast("数据错误请重试！");
            finish();
        }
//        }

//        webview.loadUrl("file:///android_asset/demo.html");
    }

    public String getOrderUrl() {
        //http://m.epfresh.com/purchase/order_detail.html

        String url = com.epfresh.api.constant.Constant.URL_ORDER_PURCHASER + SystemClock.currentThreadTimeMillis() + "&";
        String token = getUser().getAccess_token();
        String accountId = getUser().getAccountId();
        String cityId = ApplicationHelper.getInstance().getCity().getCityId();
        url = url + "access_token=" + token + "&accountId=" + accountId + "&cityId=" + cityId + "&orderId=" + orderId;
        url += "&cid=" + AppUtils.getUniquePsuedoID();
        return url;
    }

    public void webViewSetting() {
        WebSettings settings = webview.getSettings();

        settings.setJavaScriptEnabled(true);//启用js
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//js和android交互


//        settings.setAppCachePath(cacheDirPath); //设置缓存的指定路径
        settings.setAllowFileAccess(true); // 允许访问文件
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setAppCacheEnabled(false); //设置H5的缓存打开,默认关闭
        settings.setUseWideViewPort(true);//设置webview自适应屏幕大小
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//设置，可能的话使所有列的宽度不超过屏幕宽度
        settings.setLoadWithOverviewMode(true);//设置webview自适应屏幕大小
        settings.setDomStorageEnabled(true);//设置可以使用localStorage
        settings.setSupportZoom(false);//关闭zoom按钮
        settings.setBuiltInZoomControls(false);//关闭zoom
        webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        webview.setBackgroundColor(Color.TRANSPARENT);
        webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        webview.setDefaultHandler(new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                toast("" + data);
                Log.e("DefaultHandler", "functionInJs, data from web = " + data);
                function.onCallBack("返回");
            }
        });
        webview.registerHandler("submitFromWeb", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                toast("" + data);
                Log.i("submitFromWeb", "handler = submitFromWeb, data from web = " + data);
                function.onCallBack("submitFromWeb exe, response data 中文 from Java");
            }

        });
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress > 99) {
                    pb.setVisibility(View.GONE);
                } else {
                    if (pb.getVisibility() == View.GONE)
                        pb.setVisibility(View.VISIBLE);
                    pb.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (!TextUtils.isEmpty(title)) {
                    toolbarTitle.setText(title);
                    String currentUrl = view.getUrl();
                    String cleanUrl = currentUrl.replaceAll("#(.*)?", "");
                    titleMap.put(cleanUrl, title);
                }
            }


        });
        webview.setWebViewClient(new BridgeWebViewClient(webview) {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                String cleanUrl = url.replaceAll("#(.*)?", "");
                String str = titleMap.get(cleanUrl);
                if (!TextUtils.isEmpty(str)) {
                    toolbarTitle.setText(str);
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                try {
//                    url = URLDecoder.decode(url, "UTF-8");
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
                Log.e("url", "url:" + url);
//                if (url.startsWith(BridgeUtil.YY_RETURN_DATA)) { // 如果是返回数据
//                    handlerReturnData(url);
//                } else if (url.startsWith(BridgeUtil.YY_OVERRIDE_SCHEMA)) { //
//                    flushMessageQueue();
//
//                }
                if (url != null && url.startsWith("epfreshbuyerclick://product") && mContext != null) {
                    Intent intent = new Intent(mContext, DetailGoodsActivity.class);
                    String id = Uri.parse(url).getQueryParameter("id");
                    int serviceStoreId = Integer.parseInt(Uri.parse(url).getQueryParameter("storeId"));
                    intent.putExtra("storeId", Uri.parse(url).getQueryParameter("storeId"));
                    intent.putExtra("id", id);
                    intent.putExtra("serviceStoreId",serviceStoreId);
                    startActivity(intent);
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://promotionproduct") && mContext != null) {
                    Intent intent = new Intent(mContext, DetailGoodsActivity.class);
                    String id = Uri.parse(url).getQueryParameter("id");
                    String promotionId = Uri.parse(url).getQueryParameter("promotionid");
                    int serviceStoreId = Integer.parseInt(Uri.parse(url).getQueryParameter("storeId"));
                    intent.putExtra("storeId", Uri.parse(url).getQueryParameter("storeId"));
                    intent.putExtra("id", id);
                    intent.putExtra("promotionItemId", promotionId);
                    intent.putExtra("serviceStoreId",serviceStoreId);
                    startActivity(intent);
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://store") && mContext != null) {
//                    SalesType=1整货,SalesType=2散货
                    String salesType = Uri.parse(url).getQueryParameter("salestype");
                    if ("2".equals(salesType)) {
                        requestDc(false, Uri.parse(url).getQueryParameter("id"));
                    } else {
                        String id = Uri.parse(url).getQueryParameter("id");
                        Intent intent = new Intent(mContext, CommonStoreActivity.class);
                        intent.putExtra("storeId", id);
                        startActivity(intent);
                    }
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://minus") && mContext != null) {
                    Intent intent = new Intent(mContext, OrderMinusRecordActivity.class);
                    String id = Uri.parse(url).getQueryParameter("id");
                    intent.putExtra("id", id);
                    startActivity(intent);
                    Log.e(")________fadsf____", id);

                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://assess") && mContext != null) {
                    Intent evaluate = new Intent(mContext, CommentNewActivity.class);
                    String id = Uri.parse(url).getQueryParameter("id");
                    evaluate.putExtra("orderId", id);
                    startActivityForResult(evaluate, 0x001);
                    Log.e(")________fadsf____", id);

                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://order") && mContext != null) {
                    Intent intent = new Intent(mContext, OrderLogisticsInfoActivity.class);
                    String id = Uri.parse(url).getQueryParameter("id");
                    intent.putExtra("logisticsNo", id);
                    startActivity(intent);
                    Log.e(")_____________________", id);
                    return true;
                } else if (url != null && url.startsWith("tel:")) {//电话
                    Intent intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse(url));
                    startActivity(intent);
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://pay")) {//直接支付
                    Intent pay = new Intent(mContext, WXPayEntryActivity.class);
                    pay.putExtra("payWay", 1);
                    String orderId = Uri.parse(url).getQueryParameter("id");
                    pay.putExtra("orderId", orderId);
                    startActivity(pay);
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://surepay")) {//确认收货,有尾款
                    Intent pay = new Intent(mContext, WXPayEntryActivity.class);
                    String orderId = Uri.parse(url).getQueryParameter("id");
                    pay.putExtra("orderId", orderId);
                    pay.putExtra("type", "2");
                    startActivity(pay);
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://again")) {
                    Intent intent = new Intent(mContext,
                            HomeActivity.class);
                    intent.putExtra("home_tab_index", 1);
                    DataManager.getInstance().isNeedRefreshCart = true;
                    startActivity(intent);

                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://notify")) {//通知更新
                    isRefresh = true;
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://loginexc")) {//登陆异常
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    intent.putExtra("relogin", true);
                    startActivityForResult(intent, 0x001);
                    return true;
                } else if (url != null && url.startsWith("epfreshpurchaseclick://clickUpload")) {
                    photoCore.showPhotoDialog(Uri.fromFile(new File(filePath)), filePath, false);
                    return true;
                } else if (url != null && url.startsWith("epfreshpurchaseclick://comentSubmit")) {
                    String commentTip = Uri.parse(url).getQueryParameter("text");
                    T.toast(commentTip);
                    if (!TextUtils.isEmpty(commentTip) && commentTip.equals("评论成功")) {
                        setResult(RESULT_OK);
                        finish();
                    }
                    return true;

                } else {
//                    view.loadUrl(url);
                    return super.shouldOverrideUrlLoading(view, url);
                }
//                return false;
            }

//            @Override
//            public void onReceivedSslError(WebView view,
//                                           SslErrorHandler handler, SslError error) {
//                // TODO Auto-generated method stub
//                // handler.cancel();// Android默认的处理方式
//                handler.proceed();// 接受所有网站的证书
//                // handleMessage(Message msg);// 进行其他处理
//            }
        });

        webview.callHandler("functionInJs", "dffsdafsdf", new CallBackFunction() {
            @Override
            public void onCallBack(String data) {
                toast("" + data);
                Log.e("functionInJs", "functionInJs, data from web = " + data);
            }
        });
//
//        webview.send("hello");


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        photoCore.onResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x001 && resultCode == RESULT_OK) {
            webview.reload();
            isRefresh = true;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (outState == null) {
            outState = new Bundle();
        }
        outState.putString(Constant.KEY_WEB_URL, url);
        outState.putString(Constant.KEY_WEB_TITLE, title);
        outState.putInt("pushType", pushType);
        outState.putString("orderId", orderId);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onClick(View view) {
        //super.onClick(view);
        switch (view.getId()) {
            case R.id.baseback:
                // 返回上一页
                onBackPressed();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (webview.canGoBack()) {
            webview.goBack();
        } else if (pushType == 0) {
            Intent main = new Intent(getApplicationContext(), HomeActivity.class);
            startActivity(main);
            finish();
        } else if (pushType == 1) {
            finish();
        } else {
            finish();
        }
    }

    @Override
    public void finish() {
        if (isRefresh) {
            Intent intent = new Intent();
            intent.putExtra("result", true);
            intent.putExtra("page", getIntent().getIntExtra("page", 0));
            setResult(RESULT_OK, intent);
        }
        super.finish();
    }

    @Override
    protected void onDestroy() {
        if (webview != null) {
            webview.destroy();
        }
        super.onDestroy();
    }


    public void requestDc(boolean isSilent, String id) {

        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_store_dcStore);
        re.putParameter("storeId", id);
        RequestTag requestTag = new RequestTag();
        requestTag.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_store_dcStore;
        if (isSilent) {
            requestTag.type = RequestTag.TYPE_CURRENT;
            requestTag.arg1 = "silent";
            re.setCityId(ApplicationHelper.getInstance().getCity().getCityId());
            ApplicationHelper.getInstance().requestSilent(re, requestTag, onDetailRequestListener);
//                request(re, requestTag, onDetailRequestListener);
        } else {
            requestTag.arg1 = "1";
            request(re, requestTag, onDetailRequestListener);
        }

    }


    OnRequestListener<StoreDetail> onDetailRequestListener = new OnRequestListener<StoreDetail>() {
        @Override
        public StoreDetail jsonToObj(String s) {
            return new Gson().fromJson(s, StoreDetail.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

            if (o1 != null && o1 instanceof RequestTag) {
                RequestTag tag = (RequestTag) o1;
                if ("silent".equals(tag.arg1)) {

                } else {
                    hideProgressDialog();
                }
            } else {
                hideProgressDialog();
            }

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

            if (o1 != null && o1 instanceof RequestTag) {
                RequestTag tag = (RequestTag) o1;
                if ("silent".equals(tag.arg1)) {

                } else {
                    hideProgressDialog();
                }
            } else {
                hideProgressDialog();
            }

        }

        @Override
        public void onStart(Object o1) {
            if (o1 != null && o1 instanceof RequestTag) {
                RequestTag tag = (RequestTag) o1;
                if ("silent".equals(tag.arg1)) {

                } else {
                    showProgressDialog();
                }
            } else {
                showProgressDialog();
            }

        }

        @Override
        public void onResponse(ResponseEntity<StoreDetail> responseEntity, Object o1) {

            StoreDetail responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {

            }
            if (o1 != null && o1 instanceof RequestTag) {
                RequestTag tag = (RequestTag) o1;
                if ("silent".equals(tag.arg1)) {

                } else {
                    hideProgressDialog();
                    intoDcPage(responseElement);
                }
            } else {
                hideProgressDialog();
                intoDcPage(responseElement);
            }


        }
    };


    public void intoDcPage(StoreDetail responseElement) {
        if (responseElement != null) {

            if (!responseElement.isResult()) {
                Intent tv_more = new Intent(this,
                        CenterListActivity.class);
                startActivity(tv_more);
            } else {
                Intent tv_bulk_load = new Intent(this,
                        DcStoreActivity.class);
                tv_bulk_load.putExtra("data", new Gson().toJson(responseElement));
                startActivity(tv_bulk_load);
            }
        } else {

        }

    }

    @Override
    public void onSuccess(String path) {
        Log.i("照片路径：", path);
        try {
            Bitmap bitmap = BitmapFactory.decodeFile(path.replaceAll("file://", ""));
            String strBitmap = FileUtil.bitmapToBase64(bitmap);
            webview.loadUrl("javascript:getOtherUpload('" + strBitmap + "')");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFail(String msg) {

    }

    @Override
    public void onReupload() {

    }
}
